package com.neusoft.elmboot.controller;

import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.neusoft.elmboot.po.User;
import com.neusoft.elmboot.service.UserService;

@RestController
@RequestMapping("/UserController")
public class UserController {

	@Autowired
	private UserService userService;
	
	@RequestMapping("/getUserByIdByPass")
	public User getUserByIdByPass(User user) throws Exception{
		return userService.getUserByIdByPass(user.getUserId(),user.getPassword());
	}
	
	@RequestMapping("/getUserById")
	public int getUserById(String userId) throws Exception{
		return userService.getUserById(userId);
	}
	
	@RequestMapping("/saveUser")
	public int saveUser(User user) throws Exception{
		return userService.saveUser(user);
	}
	
	@RequestMapping("/changePasswordById")
	public int changePassword(User user) throws Exception{
		return userService.changePasswordById(user);
	}

	 @PostMapping("/login")
	 public String login(String userId, String password, HttpSession session, RedirectAttributes redirectAttributes) {
	     User user = userService.getUserByIdByPass(userId, password);
	     if (user != null) {
	          session.setAttribute("user", user); //登陆成功则保存用户信息到session
	          return "localhost:8081/index";
	     } else {
	          redirectAttributes.addFlashAttribute("message","Wrong username or password");
	          return "redirect:/localhost:8081/login";
	     }
	 }

	 @GetMapping("/logout")
	 public String logout(HttpSession session){
	     session.removeAttribute("user"); //退出登录则清除session中的用户信息
	     return "localhost:8081/login";
	 }

	
}
